const WebSocket = require('ws');
const WebSocketServer = WebSocket.Server

const wss = new WebSocketServer({ port: 8181 });

wss.on('connection', function connection(ws) {
    console.log('server-connection', wss)
    ws.on('message', function message(data) { 
        try {
            let parseData = JSON.parse(data)
            let loginName = ''
            let loginSex = 1
            let loginNameList = []
            console.log(parseData)
            if (parseData.loginName) {
                loginName = parseData.loginName
            }
            if (parseData.loginSex) {
                loginSex = parseData.loginSex
            }
            let index = 0
            wss.clients.forEach(function each(client) {
                if (client.readyState === WebSocket.OPEN) {
                    if (!client.loginName) {  
                        client.loginName = loginName
                    }
                    if (!loginNameList.includes(client.loginName)) {
                        loginNameList.push(client.loginName)
                    }
                    let jsonData = {
                        res: JSON.parse(data),
                        index: index,
                        loginName: loginName,
                        loginSex: loginSex,
                        loginNameList: loginNameList.join(',')
                    }
                    client.send(JSON.stringify(jsonData));
                }
                index++;
            });
        } catch (e) {
        }
  });
});